# 引入库
import requests
import json,time,re

# 区域ID
BJ_AreaID=101010100     # 北京区域ID
XA_AreaID=101110101     # 西安区域ID
BH_AreaID=101301301     # 北海区域ID
ZS_AreaID=101281701     # 中山区域ID
BL_AreaID=101300903     # 北流区域ID

# 毫秒级时间戳
Date=int(round(time.time() * 1000))

# 请求全国区域ID
def Request_AreaID():
    # 请求全国所有城市API
    API='https://j.i8tq.com/weather2020/search/city.js'
    header = {
        'Connection': 'keep-alive',
        'Referer': 'http://www.weather.com.cn/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
    }
    # 请求数据
    res = requests.get(url=API, headers=header)
    # 解码返回的数据
    buffer = res.text.encode('raw_unicode_escape').decode('unicode-escape')
    cache=json.loads(buffer[buffer.find('{'):])     # 解析JSON数据
    print(cache)



# 查询IP归属地
def Request_City():
    # IP归属地查询API
    API = 'http://wgeo.weather.com.cn/ip/?_=%s'%Date
    header = {
        'Connection': 'keep-alive',
        'Host': 'wgeo.weather.com.cn',
        'Referer': 'http://www.weather.com.cn/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
    }
    res = requests.get(url=API, headers=header)
    buffer = res.text.encode('raw_unicode_escape').decode('utf-8')
    id=re.findall('var id="(.*?)"',buffer,re.S)     # 返回的区域ID
    addr=re.findall('var addr="(.*?),(.*?),(.*?)"',buffer,re.S)     # 获取IP属地
    ip=re.findall('var ip="(.*?)"',buffer,re.S)     # 查询IP
    print("AREA_ID:%s"%int(id[0]))
    print(list(zip(id,addr,ip)))
    return zip(id,addr,ip)

# 获取天气数据
def Request_Data(A_ID):
    # 气象API
    API = "http://d1.weather.com.cn/sk_2d/%s.html?_=%s" % (A_ID,Date)
    # 请求数据头
    header = {
        'Connection': 'keep-alive',
        'Host': 'd1.weather.com.cn',
        'Referer': 'http://www.weather.com.cn/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
    }
    # 请求数据
    res = requests.get(url=API, headers=header)
    buffer=res.text.encode('raw_unicode_escape').decode('utf-8')
    cache = json.loads(buffer[11:])  # 解码JSON为字典
    # 处理报文
    tmp = {
            '城市：': cache['cityname'],
            '温度：': str(cache['temp']) + '℃',
            '风向：': cache['WD'],
            '风力：': cache['WS'],
            '风速：': cache['wse'],
            '湿度：': cache['SD'],
            '气压：': str(cache['qy'])+'hPa',
            '能见度：': cache['njd'],
            '雨量：': cache['rain'],
            'API：': cache['aqi'],
            'PM2.5：': cache['aqi_pm25'],
            '天气：': cache['weather'],
            '日期：': cache['date']
        }
    return tmp # 输出气象数据

if __name__ =='__main__':
    AreaID=list(Request_City())[0][0]
    W_Info=Request_Data(AreaID)
    print(W_Info)